package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求对象
 * 该类的每一个实例用于表示HTTP协议规定的客户端发送过来的一个请求内容
 * 每个请求由三部分构成
 * 请求行，消息头，消息正文
 */
public class HttpServletRequest {

    //消息头相关信息
    private Map<String,String> headers = new HashMap<>();

    //请求行的相关信息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议

    private Socket socket;
    /**
     * 实例化请求对象的过程也是解析的过程
     */
    public HttpServletRequest(Socket socket ) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();

        //1.2解析消息头
        parseHeaders();

        //1.3解析消息正文
        parseContent();



    }
    /*
        解析请求行
     */
    private void parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println(line);

        String[] m =  line.split(" ");
        method = m[0];
        uri = m[1];
        protocol = m[2];

        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protoval:"+protocol);
    }
    /*
        解析消息头
     */
    private void parseHeaders() throws IOException {

        while (true){
            String line =  readLine();
            if (line.isEmpty()) {
                break;
            }
            String[] str = line.split(": ");
            headers.put(str[0],str[1]);
//                System.out.println("消息头："+line);
        }
        System.out.println("headers:"+headers);
//            while (line.length() != 0){
//                line = readLine();
//                System.out.println(line);
//            }
    }
    /*
        解析消息正文
     */
    private void parseContent(){}

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char pre = ' ',cur = ' ';//pre上次读的字符，cur本次读的字符
        int d ;
        while((d = in.read())!=-1){
            cur = (char) d;
            if (pre ==13&& cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    /**
     * 根据给定的消息头的名字获取对应的值
     * @param name
     * @return
     */
    public String getHeader(String name){
        return headers.get(name);
    }
}
